import tkinter as tk
from tkinter import messagebox, font, scrolledtext, ttk, filedialog
from PIL import Image, ImageTk
import json
import requests
import logging
from datetime import datetime
import os
from docx import Document
from docx.shared import RGBColor
from docx.oxml.ns import qn
import asyncio
import threading
import random

# Configure logging
logging.basicConfig(filename='conversation.log', level=logging.DEBUG, 
                   format='%(asctime)s - %(levelname)s - %(message)s')

# Add relationship prompts dictionary at the top level
relationship_prompts = {
    1: "你们关系很差，经常争吵和反对对方",
    2: "你们关系一般，经常有不同意见", 
    3: "你们关系正常，可以理性讨论",
    4: "你们关系不错，经常互相支持",
    5: "你们关系很好，总是赞同对方"
}

# Add async support for tkinter
def async_handler(async_func):
    def wrapper(*args, **kwargs):
        def run():
            try:
                asyncio.run(async_func(*args, **kwargs))
            except Exception as e:
                logging.error(f"Async error: {str(e)}")
                messagebox.showerror("错误", f"对话过程中出错：{str(e)}")
        threading.Thread(target=run).start()
    return wrapper

# Add color palettes
ICON_COLORS = ['#ffffff', '#95EC69', '#9999ff', '#ffff99', '#ff99ff']  # White, WeChat Green, Blue, Yellow, Purple
BUBBLE_COLORS = {
    '翠花': ['#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff'],  # White
    '大強': ['#ebf9e2', '#dff6d4', '#c6edaf', '#aae48c', '#95EC69'],  # Green shades
    '阿珍': ['#ececff', '#ddddff', '#ceceff', '#bfbfff', '#b0b0ff'],  # Blue shades
    '老王': ['#ffffec', '#ffffdd', '#ffffce', '#ffffbf', '#ffffb0'],  # Yellow shades
    '老登': ['#ffecff', '#ffddff', '#ffceff', '#ffbfff', '#ffb0ff']   # Purple shades
}

# After importing modules, add these color and style constants
COLORS = {
    'primary': '#2196F3',      # Material Blue
    'secondary': '#FF4081',    # Pink accent
    'success': '#4CAF50',      # Material Green
    'warning': '#FFC107',      # Material Amber
    'danger': '#F44336',       # Material Red
    'light': '#FAFAFA',        # Almost white
    'dark': '#212121',         # Almost black
    'background': '#F5F5F5',   # Light grey background
    'card': '#FFFFFF',         # White for cards
}

# After the COLORS definition and before the ChatMessage class, add:
DEFAULT_FONT = ('Microsoft YaHei UI', 11)
DEFAULT_FONT_BOLD = ('Microsoft YaHei UI', 11, 'bold')

class ChatMessage(tk.Frame):
    def __init__(self, master, message, is_right=False, relationship_level=3, name="", **kwargs):
        super().__init__(master, **kwargs)
        self.configure(bg=COLORS['background'])
        
        # Validate name and ensure proper font for Chinese characters
        if not name:
            name = "翠花"  # Default to 翠花 if empty
            
        # Create icon frame
        icon_frame = tk.Frame(self, bg=COLORS['background'])
        if is_right:
            icon_frame.pack(side=tk.RIGHT, padx=(5, 10))
        else:
            icon_frame.pack(side=tk.LEFT, padx=(10, 5))
            
        # Get participant index for color
        participant_names = list(BUBBLE_COLORS.keys())
        participant_index = participant_names.index(name) if name in participant_names else 0
        icon_color = ICON_COLORS[participant_index % len(ICON_COLORS)]
        
        # Create colored circle as icon
        img = Image.new('RGB', (50, 50), icon_color)
        photo = ImageTk.PhotoImage(img)
            
        # Add icon and name label with proper font configuration
        icon_label = tk.Label(icon_frame, image=photo, bg=COLORS['background'])
        icon_label.image = photo
        icon_label.pack()
        
        # Use tk.Label with specific font configuration for Chinese
        name_label = tk.Label(icon_frame, text=name, 
                            font=('Microsoft YaHei UI', 12, 'bold'),
                            bg=COLORS['background'])
        name_label.pack()
        
        # Add random emoji to message with 30% probability
        emojis = ['😊', '😄', '👍', '🤔', '💡', '✨', '🎉']
        if random.random() < 0.3:
            message += f" {random.choice(emojis)}"
            
        # Create message with participant-specific colors
        bubble_colors = BUBBLE_COLORS.get(name, BUBBLE_COLORS['翠花'])  # Default to 翠花's colors if name not found
        msg_frame = tk.Frame(self, bg=bubble_colors[relationship_level-1])
        msg_frame.pack(side=tk.RIGHT if is_right else tk.LEFT, padx=5)
            
        # Use tk.Label with specific font configuration for Chinese message
        msg_label = tk.Label(msg_frame, text=message, wraplength=600, 
                            justify=tk.LEFT, bg=msg_frame['bg'],
                            font=('Microsoft YaHei UI', 14))
        msg_label.pack(padx=15, pady=10)

def ask_deepseek(prompt, deepseek_api_key):
    try:
        response = requests.post(
            "https://api.deepseek.com/v1/chat/completions",
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {deepseek_api_key}"
            },
            data=json.dumps(prompt)
        )
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        logging.error(f"Error making API request: {e}")
        raise

# Create main window first
root = tk.Tk()
root.title("开会喽")
root.geometry("1200x900")

# Add custom styles after creating the root window
style = ttk.Style()
style.configure('Modern.TFrame', background=COLORS['background'])
style.configure('Card.TFrame', background=COLORS['card'])
style.configure('Modern.TLabel', background=COLORS['background'], font=('Microsoft YaHei UI', 12))
style.configure('Header.TLabel', background=COLORS['background'], font=('Microsoft YaHei UI', 14, 'bold'))
style.configure('Modern.TEntry', font=('Microsoft YaHei UI', 11))
style.configure('Modern.TButton', font=('Microsoft YaHei UI', 11))

# Update the root window configuration
root.configure(bg=COLORS['background'])
root.option_add("*Font", ('Microsoft YaHei UI', 11))

# Initialize all global variables
relationship_level = 3
name_a_text = "A"
name_b_text = "B"
settings = None

def generate_minutes():
    try:
        # Validate inputs
        if not conversation_history:
            messagebox.showwarning("警告", "没有对话内容可以生成纪要")
            return
            
        topic = topic_text.get("1.0", tk.END).strip()
        if not topic:
            messagebox.showwarning("警告", "请输入讨论主题")
            return
            
        # Create document with default font
        doc = Document()
        
        # Set default font for entire document
        style = doc.styles['Normal']
        style.font.name = '仿宋'
        style._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
        
        # Set font for all other styles
        for style in doc.styles:
            if hasattr(style, 'font'):
                style.font.name = '仿宋'
                style._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
        
        # Create summary prompt with explicit formatting instructions
        summary_prompt = {
            "model": "deepseek-chat",
            "messages": [
                {"role": "system", "content": """你是一个专业的会议纪要撰写者。
                请总结对话内容的要观点和结论。
                请使用普通文本格式输出，不要使用markdown格式。
                请分点列出重要内容，每点都用完整的句子描述。
                """},
                {"role": "user", "content": f"主题：{topic_text.get('1.0', tk.END).strip()}\n\n" + "\n".join(conversation_history)}
            ]
        }
        
        # Get summary from deepseek
        response = ask_deepseek(summary_prompt, api_entry.get())
        summary = response["choices"][0]["message"]["content"]
        
        # Add title
        title = f"会议纪要 - {topic_text.get('1.0', tk.END).strip()}"
        doc.add_heading(title, 0)
        
        # Add metadata
        doc.add_paragraph(f"日期时间：{datetime.now().strftime('%Y-%m-%d %H:%M')}")
        doc.add_paragraph(f"讨论主题：{topic_text.get('1.0', tk.END).strip()}")
        doc.add_paragraph(f"对话轮数：{rounds_entry.get()}")
        doc.add_paragraph(f"关系程度：{relationship_level}")
        
        # Add summary
        doc.add_heading("讨论要点总结", 1)
        summary_para = doc.add_paragraph()
        summary_para.add_run(summary)
        
        # Add full conversation
        doc.add_heading("详细对话记录", 1)
        for msg in conversation_history:
            p = doc.add_paragraph()
            run = p.add_run(msg)
            run.font.name = '仿宋'
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
        
        # Save document
        filename = f"会议纪要_{datetime.now().strftime('%Y%m%d_%H%M')}.docx"
        doc.save(filename)
        messagebox.showinfo("成功", f"会议纪要已保存为：{filename}")
        
    except Exception as e:
        error_msg = f"生成会议纪要时出错：{str(e)}"
        logging.error(error_msg)
        messagebox.showerror("错误", error_msg)

def validate_rounds():
    try:
        rounds = int(rounds_entry.get())
        if rounds < 1:
            rounds = 1
        elif rounds > 100:
            rounds = 100
        rounds_entry.delete(0, tk.END)
        rounds_entry.insert(0, str(rounds))
        return rounds
    except ValueError:
        rounds_entry.delete(0, tk.END)
        rounds_entry.insert(0, "5")
        return 5

def add_reference():
    file_path = filedialog.askopenfilename(
        title="选择参考文档",
        filetypes=[("Text files", "*.txt"), ("Word files", "*.docx"), ("All files", "*.*")]
    )
    if file_path:
        try:
            if file_path.endswith('.docx'):
                doc = Document(file_path)
                content = '\n'.join([paragraph.text for paragraph in doc.paragraphs])
            else:
                with open(file_path, 'r', encoding='utf-8') as file:
                    content = file.read()
            reference_text.delete('1.0', tk.END)
            reference_text.insert('1.0', content)
        except Exception as e:
            messagebox.showerror("错误", f"读取文件时出错：{str(e)}")

def clear_conversation():
    global conversation_history, messages
    conversation_history = []
    messages = []  # Reset messages list
    for widget in chat_frame.winfo_children():
        widget.destroy()
    chat_canvas.yview_moveto(0)  # Scroll back to top

# Add typing indicator function
def show_typing_indicator(name, is_right=False):
    msg_frame = ChatMessage(chat_frame, f"{name} 正在输入...", 
                          is_right=is_right, 
                          relationship_level=relationship_level,
                          name=name)
    msg_frame.pack(fill=tk.X, padx=10, pady=5)
    chat_canvas.update_idletasks()
    chat_canvas.yview_moveto(1.0)
    return msg_frame

# Add completion message function
def show_completion_message():
    msg_frame = ChatMessage(chat_frame, "对话已结束", 
                          is_right=False, 
                          relationship_level=3)
    msg_frame.pack(fill=tk.X, padx=10, pady=5)
    chat_canvas.update_idletasks()
    chat_canvas.yview_moveto(1.0)

# Add leader prompts
LEADER_PROMPTS = {
    "opening": """你是讨论的领导者{name}，{personality}。
                作为领导者，你需要:
                1. 用1-3句话简短发言
                2. 提出开放性问题邀请其他人发表看法
                3. 确保讨论围绕主题展开
                
                讨论主题是：{topic}
                {objective}
                
                请用1-3句话开启讨论，并邀请其他人发表意见。""",
                
    "summarize": """作为领导者，请用1-3句话:
                1. 总结目前讨论的要点
                2. 引导讨论进入下一个方面
                要用自然的语气。""",
                
    "conclude": """作为领导者，请用1-3句话:
                1. 总结大家达成的共识
                2. 提出下一步建议或行动计划
                要用自然的语气。"""
}

DISCUSSANT_PROMPT = """你是{name}，请严格按照以下性格特征来塑造对话：
{personality}

你和对方的关系是：{relationship}
                    
在对话中，你必须：
1. 用1-2句话简短发言
2. 严格展现你独特的性格特点：{personality}
3. 根据关系程度互动：
   - 关系很差(1级)时：必须表不同意见，可以直接反驳或质疑对方
   - 关系一般(2级)时：可以委婉地表达不同看法
   - 关系正常(3级)时：可以理性讨论，既可以同意也可以不同意
   - 关系不错(4级)时：多表示认同，偶尔提出补充
   - 关系很好(5级)时：要积极支持对方观点

4. 每句话都要体现你的性格特征，不能前后矛盾
5. 对话要自然不要太正式或做作
                    
讨论主题是：{topic}
{objective}
                    
请以符合你性格和关系程度的方式回应之前的发言。记住：你的每句话都要反映出你的性格特征。"""

# Update personality suggestions with new Chinese names
PERSONALITY_SUGGESTIONS = [
    ("翠花", "性格外向开朗，喜欢与人交流，经常提出新想法"),
    ("大強", "性格内向谨慎，善于思考和分析，喜欢深入研究"),
    ("阿珍", "性格活泼热情，富有同理心，善于调节气氛"),
    ("老王", "性格沉稳理性，逻辑性强，善于总结归纳"),
    ("老登", "性格随和友善，善于倾听，喜欢帮助他人")
]

# Add village personality template
VILLAGE_PERSONALITIES = [
    ("翠花", "ISFJ, 村里的'小燕子', 总是忙忙碌碌, 但她的忙碌不是在筑巢, 而是在村里的八卦圈里飞来飞去。她对村里的大事小情了如指掌, 但别指望她能保守秘密, 为'小燕子'的嘴比村口的大喇叭还快。"),
    ("大強", "ENTJ, 纯纯的气氛组, 什么都不懂。爱游玩, 爱喝啤酒, 平时在村口蹓跶。不过, 他还有个隐藏技能——只要他一出现, 气氛就能从零下冰点飙升到热带风暴, 他的存在就是派对的保证。"),
    ("阿珍", "ENFP, 村里的'心灵导师', 她总是能从口袋里掏出一颗糖, 让你的心情瞬间变甜。她的热情能点燃最冷漠的心, 但她的健忘也能让村里的大事变成'昨天的事'。别问她昨天的会议说了啥, 她可能连昨天吃的啥都忘了。"),
    ("老王", "ISTJ, 村里的'时间守护者'。他的生活比钟表还准时, 每天日出而作, 日落而息, 连村里的鸡都以他的作息为标准。如果你想知道他在干嘛, 看看时钟就知道了。不过, 千万别在他午休的时候打扰他, 否则你会见识到'时间守护者'的另一面——'午睡守护神'。"),
    ("老登", "ESFP, 村里的'活动导演'。哪里有热闹, 哪里就有老登。他能把任何地方变成舞台, 任何时候变成派对。他的口头禅是:'生活不止眼前的苟且, 还有诗和远的啤酒节。'他的存在就是为了证明, 即使是在村里, 也能活出不村的人生。")
]

@async_handler
async def start_conversation():
    global conversation_history, messages
    conversation_history = []  # Clear history
    messages = []  # Reset messages list
    
    # Get inputs
    topic = topic_text.get("1.0", tk.END).strip()
    api_key = api_entry.get()
    rounds = validate_rounds()
    reference = reference_text.get("1.0", tk.END).strip()
    objective = objective_text.get("1.0", tk.END).strip()
    
    if not topic or not api_key:
        messagebox.showwarning("输入错误", "请输入讨论主题和API密钥")
        return
        
    # Clear conversation display
    for widget in chat_frame.winfo_children():
        widget.destroy()
    
    # Get participants from settings
    participants = settings['participants']
    
    # Simplified prompts
    reference_prompt = f"\n参考资料：{reference}" if reference else ""
    objective_prompt = f"\n讨论目标：{objective}" if objective else ""
    
    messages = []  # Initialize empty messages list
    
    try:
        # Find leader
        leader = next((p for p in participants if p.role == "leader"), None)
        discussants = [p for p in participants if p.role == "discussant"]
        
        # Leader starts the discussion
        if leader:
            typing_indicator = show_typing_indicator(leader.name, is_right=False)
            
            # Use opening prompt for leader
            prompt = {
                "model": "deepseek-chat",
                "messages": [
                    {"role": "system", "content": LEADER_PROMPTS["opening"].format(
                        name=leader.name,
                        personality=leader.personality,
                        topic=topic,
                        objective=objective_prompt
                    )},
                    {"role": "user", "content": f"请开始讨论主题：{topic}"}
                ]
            }
            
            response = await asyncio.to_thread(ask_deepseek, prompt, api_key)
            typing_indicator.destroy()
            
            message = response["choices"][0]["message"]["content"]
            msg_frame = ChatMessage(chat_frame, message, is_right=False, 
                                  relationship_level=relationship_level, name=leader.name)
            msg_frame.pack(fill=tk.X, padx=10, pady=5)
            messages.append({"role": "assistant", "content": message})
            conversation_history.append(f"{leader.name}: {message}")
            
            await asyncio.sleep(0.1)
        
        # Rest of conversation loop
        for round_num in range(rounds):
            # Keep context for better dialogue flow
            recent_history = messages[-3:] if messages else []
            
            # Discussants' turns
            for i, participant in enumerate(discussants):
                is_right = (i % 2 == 1)
                typing_indicator = show_typing_indicator(participant.name, is_right=is_right)
                
                # Use updated discussant prompt
                prompt = {
                    "model": "deepseek-chat",
                    "messages": [
                        {"role": "system", "content": DISCUSSANT_PROMPT.format(
                            name=participant.name,
                            personality=participant.personality,
                            relationship=relationship_level,
                            topic=topic,
                            objective=objective_prompt
                        )},
                        {"role": "user", "content": "请对之前的发言做出回应。"}
                    ] + recent_history
                }
                
                response = await asyncio.to_thread(ask_deepseek, prompt, api_key)
                typing_indicator.destroy()
                
                message = response["choices"][0]["message"]["content"]
                msg_frame = ChatMessage(chat_frame, message, is_right=is_right, 
                                      relationship_level=relationship_level, name=participant.name)
                msg_frame.pack(fill=tk.X, padx=10, pady=5)
                messages.append({"role": "assistant", "content": message})
                conversation_history.append(f"{participant.name}: {message}")
                
                await asyncio.sleep(0.1)
            
            # Leader summarizes every few rounds
            if leader and (round_num + 1) % 2 == 0:
                typing_indicator = show_typing_indicator(leader.name, is_right=False)
                
                prompt = {
                    "model": "deepseek-chat", 
                    "messages": [
                        {"role": "system", "content": LEADER_PROMPTS["summarize"]},
                        {"role": "user", "content": "请总结并引导讨论"}
                    ] + recent_history
                }
                
                response = await asyncio.to_thread(ask_deepseek, prompt, api_key)
                typing_indicator.destroy()
                
                message = response["choices"][0]["message"]["content"]
                msg_frame = ChatMessage(chat_frame, message, is_right=False, 
                                      relationship_level=relationship_level, name=leader.name)
                msg_frame.pack(fill=tk.X, padx=10, pady=5)
                messages.append({"role": "assistant", "content": message})
                conversation_history.append(f"{leader.name}: {message}")
                
                await asyncio.sleep(0.1)
    
    except Exception as e:
        error_msg = f"对话过程中出错：{str(e)}"
        logging.error(error_msg)
        messagebox.showerror("错误", error_msg)
    
    show_completion_message()

# Add participant class to store info
class Participant:
    def __init__(self, name="", personality="", role="discussant"):
        self.name = name
        self.personality = personality
        self.role = role
        self.messages = []

class SettingsWindow(tk.Toplevel):
    def __init__(self, parent, current_settings=None):
        super().__init__(parent)
        self.title("角色设置")
        self.geometry("1000x800")
        self.configure(bg=COLORS['background'])
        
        # Initialize result
        self.result = None
        self.current_template = "default"  # Track current template
        
        if current_settings is None:
            current_settings = {
                'num_participants': 2,
                'participants': [],
                'relationship': 3
            }
            
        # Create settings UI
        settings_frame = ttk.Frame(self, style='Modern.TFrame', padding="20")
        settings_frame.pack(fill=tk.BOTH, expand=True)
        
        # Add template selection buttons
        template_frame = ttk.Frame(settings_frame)
        template_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(template_frame, text="选择角色模板:", 
                 font=('Microsoft YaHei UI', 11)).pack(side=tk.LEFT, padx=5)
        
        tk.Button(template_frame, text="默认模板", 
                 command=lambda: self.switch_template("default"),
                 bg=COLORS['primary'], fg='white',
                 font=('Microsoft YaHei UI', 11),
                 relief="flat",
                 cursor="hand2").pack(side=tk.LEFT, padx=5)
        
        tk.Button(template_frame, text="快乐模板", 
                 command=lambda: self.switch_template("village"),
                 bg=COLORS['secondary'], fg='white',
                 font=('Microsoft YaHei UI', 11),
                 relief="flat",
                 cursor="hand2").pack(side=tk.LEFT, padx=5)
        
        # Number of participants
        num_frame = ttk.Frame(settings_frame)
        num_frame.pack(fill=tk.X, pady=10)
        
        ttk.Label(num_frame, text="参与人数 (2-5):", 
                 font=('Microsoft YaHei UI', 11)).pack(side=tk.LEFT, padx=5)
        self.num_participants = ttk.Spinbox(num_frame, from_=2, to=5, width=5, 
                                          command=self.update_participant_fields)
        self.num_participants.set(current_settings['num_participants'])
        self.num_participants.pack(side=tk.LEFT, padx=5)
        
        # Participants frame
        self.participants_frame = ttk.Frame(settings_frame)
        self.participants_frame.pack(fill=tk.BOTH, expand=True)
        
        # Relationship scale with updated label
        rel_frame = ttk.Frame(settings_frame)
        rel_frame.pack(fill=tk.X, pady=10)
        
        ttk.Label(rel_frame, text="群体关系:", 
                 font=('Microsoft YaHei UI', 11)).pack(side=tk.TOP, pady=5)
        ttk.Label(rel_frame, text="对立", 
                 font=('Microsoft YaHei UI', 11)).pack(side=tk.LEFT, padx=5)
        self.relationship = ttk.Scale(rel_frame, from_=1, to=5, orient=tk.HORIZONTAL)
        self.relationship.set(current_settings['relationship'])
        self.relationship.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)
        ttk.Label(rel_frame, text="和谐", 
                 font=('Microsoft YaHei UI', 11)).pack(side=tk.LEFT, padx=5)
        
        # Submit button
        tk.Button(settings_frame, text="确认", command=self.save_settings,
                 bg=COLORS['success'], fg='white', 
                 font=DEFAULT_FONT_BOLD,
                 relief="flat",
                 padx=20, pady=10,
                 cursor="hand2").pack(pady=20)
        
        self.participant_entries = []
        self.update_participant_fields()
        
        # Wait for window to close
        self.wait_window()
        
    def update_participant_fields(self):
        # Clear existing fields
        for widget in self.participants_frame.winfo_children():
            widget.destroy()
        
        num = int(self.num_participants.get())
        self.participant_entries = []
        
        for i in range(num):
            frame = ttk.Frame(self.participants_frame)
            frame.pack(fill=tk.X, pady=10)
            
            # Name with Chinese default
            ttk.Label(frame, text=f"人物{i+1}名称:", 
                     font=DEFAULT_FONT).pack(side=tk.LEFT, padx=5)
            name_entry = ttk.Entry(frame, width=10, font=DEFAULT_FONT)
            name_entry.pack(side=tk.LEFT, padx=5)
            name_entry.insert(0, PERSONALITY_SUGGESTIONS[i % len(PERSONALITY_SUGGESTIONS)][0])
            
            # Personality with larger height and width, smaller font
            personality_text = tk.Text(frame, height=4, width=50,
                                     font=DEFAULT_FONT)
            personality_text.pack(side=tk.LEFT, padx=5)
            personality_text.insert("1.0", PERSONALITY_SUGGESTIONS[i % len(PERSONALITY_SUGGESTIONS)][1])
            
            # Role (radio buttons)
            role_frame = ttk.Frame(frame)
            role_frame.pack(side=tk.LEFT, padx=5)
            role_var = tk.StringVar(value="discussant")
            ttk.Radiobutton(role_frame, text="领导者", variable=role_var, 
                           value="leader", style='Large.TRadiobutton').pack(side=tk.LEFT)
            ttk.Radiobutton(role_frame, text="讨论者", variable=role_var, 
                           value="discussant", style='Large.TRadiobutton').pack(side=tk.LEFT)
            
            self.participant_entries.append((name_entry, personality_text, role_var))
            
    def save_settings(self):
        num = int(self.num_participants.get())
        participants = []
        
        for name_entry, personality_text, role_var in self.participant_entries:
            participant = Participant(
                name=name_entry.get().strip() or chr(65 + len(participants)),
                personality=personality_text.get("1.0", tk.END).strip(),
                role=role_var.get()
            )
            participants.append(participant)
            
        self.result = {
            'num_participants': num,
            'participants': participants,
            'relationship': int(self.relationship.get())
        }
        self.destroy()

    def switch_template(self, template):
        self.current_template = template
        # Update all participant fields with new template
        for i, (name_entry, personality_text, _) in enumerate(self.participant_entries):
            if i < len(self.participant_entries):
                if template == "village":
                    name, personality = VILLAGE_PERSONALITIES[i]
                else:
                    name, personality = PERSONALITY_SUGGESTIONS[i]
                
                name_entry.delete(0, tk.END)
                name_entry.insert(0, name)
                
                personality_text.delete("1.0", tk.END)
                personality_text.insert("1.0", personality)

def show_settings():
    global settings
    settings_window = SettingsWindow(root, settings)  # Pass current settings
    if settings_window.result is not None:
        settings = settings_window.result

# Show settings window on startup
show_settings()

# Create simplified main interface
main_frame = ttk.Frame(root)
main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)

# Left column for inputs
left_frame = ttk.Frame(main_frame)
left_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 10))

# Settings button
tk.Button(left_frame, text="修改角色设置", command=show_settings,
          bg=COLORS['secondary'], fg='white', 
          font=('Microsoft YaHei UI', 12),
          relief="flat",
          padx=15, pady=8,
          cursor="hand2").pack(pady=10, fill=tk.X)

# Input frame
input_frame = ttk.LabelFrame(left_frame, text="基本设置")
input_frame.pack(fill=tk.X, pady=5)

# Topic input
tk.Label(input_frame, text="讨论主题:", font=DEFAULT_FONT).pack(pady=5)
topic_text = tk.Text(input_frame, height=2, width=30, font=DEFAULT_FONT)
topic_text.pack(pady=5)

# Dialog objective input
tk.Label(input_frame, text="对话目标 (选填):", font=DEFAULT_FONT).pack(pady=5)
objective_text = tk.Text(input_frame, height=4, width=30, font=DEFAULT_FONT)
objective_text.pack(pady=5)

# API key entry
tk.Label(input_frame, text="Deepseek API密钥:", font=DEFAULT_FONT).pack(pady=5)
api_entry = tk.Entry(input_frame, width=30, font=DEFAULT_FONT)
api_entry.pack(pady=5)
api_entry.insert(0, "sk-271298e918124857b6c9c3a8faa75cd6")

# Number of rounds entry
tk.Label(input_frame, text="对话轮数 (1-100):", font=DEFAULT_FONT).pack(pady=5)
rounds_entry = tk.Entry(input_frame, width=10, font=DEFAULT_FONT)
rounds_entry.pack(pady=5)
rounds_entry.insert(0, "5")

# Add start conversation button
tk.Button(input_frame, text="开始对话", command=start_conversation,
          bg=COLORS['success'], fg='white',
          font=('Microsoft YaHei UI', 12, 'bold'),
          relief="flat",
          padx=20, pady=10,
          cursor="hand2").pack(pady=15, fill=tk.X, padx=10)

# Add reference document frame first
reference_frame = ttk.LabelFrame(left_frame, text="参考资料")
reference_frame.pack(fill=tk.X, pady=5)

reference_button = tk.Button(reference_frame, text="➕ 添加参考文", 
                           command=add_reference, 
                           font=DEFAULT_FONT,
                           bg=COLORS['primary'], 
                           fg='white',
                           relief="flat",
                           cursor="hand2")
reference_button.pack(pady=5, fill=tk.X, padx=5)

reference_text = tk.Text(reference_frame, height=4, width=30, font=DEFAULT_FONT)
reference_text.pack(pady=5, padx=5)

# Add clear conversation button next
clear_button = tk.Button(left_frame, text="清空对话", command=clear_conversation,
                        bg=COLORS['danger'], fg='white',
                        font=('Microsoft YaHei UI', 12),
                        relief="flat",
                        padx=15, pady=8,
                        cursor="hand2").pack(pady=10, fill=tk.X)

# Right column for chat
right_frame = ttk.Frame(main_frame)
right_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

# Chat frame with scrollbar
chat_frame_outer = ttk.Frame(right_frame)
chat_frame_outer.pack(fill=tk.BOTH, expand=True)

chat_canvas = tk.Canvas(chat_frame_outer, bg='#f0f0f0')
scrollbar = ttk.Scrollbar(chat_frame_outer, orient="vertical", command=chat_canvas.yview)
chat_frame = tk.Frame(chat_canvas, bg='#f0f0f0')

# Configure scrolling
chat_canvas.configure(yscrollcommand=scrollbar.set)
chat_canvas.create_window((0, 0), window=chat_frame, anchor='nw', width=800)

# Pack scrollbar next to canvas
chat_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

def configure_scroll_region(event):
    chat_canvas.configure(scrollregion=chat_canvas.bbox("all"))
chat_frame.bind('<Configure>', configure_scroll_region)

# Add generate minutes button at bottom
tk.Button(right_frame, text="生成会议纪要", command=generate_minutes,
          bg=COLORS['primary'], fg='white',
          font=('Microsoft YaHei UI', 12, 'bold'),
          relief="flat",
          padx=20, pady=10,
          cursor="hand2").pack(pady=15)

# Create custom style for larger radio buttons
style = ttk.Style()
style.configure('Large.TRadiobutton', font=('Microsoft YaHei', 16, 'bold'))

# Start the main loop
root.mainloop() 